﻿using System;
using System.Linq;
using System.Reflection;
using EventBus.Common;
using Microsoft.Extensions.DependencyInjection;

namespace EventBus.Kafka
{
    /// <summary>
    /// 订阅者注册缓存
    /// </summary>
    public static class RegisterSubscriber
    {
        /// <summary>
        /// 注册Handler
        /// </summary>
        /// <param name="service"></param>
        /// <param name="assemblyName"></param>
        public static void RegisterHandler(this IServiceCollection service, string assemblyName)
        {
            if (string.IsNullOrEmpty(assemblyName))
                throw new ArgumentNullException(nameof(assemblyName));
            var assembly = RuntimeHelper.GetAssembly(assemblyName);
            if (assembly == null)
            {
                throw new DllNotFoundException($"the dll \"{assemblyName}\" not be found");
            }
            var typeList = assembly.GetTypes().Where(t => t.GetTypeInfo().IsClass);
            foreach (var type in typeList)
            {
                //注册CommandHandler
                var interfacesCommandTypeList = type.GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == GetGenericCommandHandlerType());
                foreach (var interfacesType in interfacesCommandTypeList)
                {
                    service.AddSingleton(interfacesType, type);
                }
                //注册EventHandler
                var interfacesEventTypeList = type.GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == GetGenericEventHandlerType());
                foreach (var interfacesType in interfacesEventTypeList)
                {
                    service.AddSingleton(interfacesType, type);
                }
            }
        }

        /// <summary>
        /// 获取CommandHandler的类型
        /// </summary>
        /// <returns></returns>
        public static Type GetGenericCommandHandlerType()
        {
            return typeof(ICommandHandler<>);
        }

        /// <summary>
        ///   /// <summary>
        /// 获取EventHandler的类型
        /// </summary>
        /// <returns></returns>
        /// </summary>
        /// <returns></returns>
        public static Type GetGenericEventHandlerType()
        {
            return typeof(IEventHandler<>);
        }

    }
}
